const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const formatDate = date => {
  let year = date.getFullYear();
  let month = date.getMonth() + 1;
  let day = date.getDate();
  return [year, month, day].map(formatNumber).join('-')
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}

/**
 * @author hhk
 * @date 2021-07-22
 * @description 字符串判空
 */
const isNullOrEmpty = str => {
  return typeof (str) == "undefined" || str == null || str == "";
}

/**
 * @author hhk
 * @date 2021-08-09
 * @description 对象判空
 */
const objIsNull = obj => {
  return typeof (obj) == "undefined" || !obj || JSON.stringify(obj) == "{}";
}

/**
 * @author hhk
 * @date 2021-08-09
 * @description 表单验证是否填写完整
 */
const formValidation = form => {
  for (let item in form) {
    if (!form[item] || form[item] == '') {
      return false;
    }
  }
  return true;
}

/**
 * 对象数组内根据某个参数排序
 * @params props 对象参数的名字
 * @author hhk
 * @date 2021-08-30
 */
function sortBy(props) {
  return function (a, b) {
    return a[props] - b[props]; // 如果a>=b，返回自然数，不用交换位置
  }
}

/**
 * 对象数组内根据时间参数排序
 * 注意：a[props]和b[props]不可以为空或undefinded，否则会报 Cannot read property ‘replace‘ of undefined
 * @params sign 要替换的符号
 * @params props 对象参数名字
 * @author hhk
 * @date 2021-08-30
 */
function dateTimeSortBy(sign, props) {
  return function (a, b) {
    let str = new RegExp(sign, 'g');
    // 把时间参数的格式转换成 YYYY-MM-DD hh:mm:ss
    // 然后再parse
    let t1 = new Date(Date.parse(a[props].replace(str, "/")));
    let t2 = new Date(Date.parse(b[props].replace(str, "/")));
    return t2.getTime() - t1.getTime();
  }
}

module.exports = {
  formatTime: formatTime,
  formatDate: formatDate,
  isNullOrEmpty: isNullOrEmpty,
  objIsNull: objIsNull,
  formValidation: formValidation,
  sortBy: sortBy,
  dateTimeSortBy: dateTimeSortBy
}